/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package uit.jee.lib.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import uit.jee.lib.access.mapper.BookMapper;
import uit.jee.lib.bo.BookBO;
import uit.jee.lib.dto.BookDTO;

/**
 *
 * @author ngloc_it
 */
@WebServlet(name="HomePage", urlPatterns={"/HomePage"})
public class HomePage extends HttpServlet {
   
     // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
       
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");//set tieng viet
        HttpSession session = req.getSession();//lay ve session

        String function = req.getParameter("function");//Trang hien co nhieu phan
        //moi phan co nhiem vu khac, can 1 function de truyen vao

        if (function.equalsIgnoreCase("reloadbook")){
            ReloadBook(resp);
            return;
        }

        try {
            //Load top 10 best book.
            ArrayList<BookDTO> books = loadTopTenBook();
            if ((books != null)
                    && (!books.isEmpty())) {
                session.setAttribute("topbooks", books);//gan vo session sau khi co sach
            }

            BookDTO book = new BookBO().getRandomBook();
            if ((book != null)
                    && (book.checkValidate())) {
                session.setAttribute("bookrandom", book);
            }
        } catch (Exception ex) {
            Logger.getLogger(HomePage.class.getName()).log(Level.SEVERE, null, ex);
        }

        String path = "./jsps/HomePage.jsp";
        resp.sendRedirect(path);//sau khi co du lieu roi thi chuyen qua VIEW
    }

    /**
     * Get top 10 book, and one random
     * the random one is put at tail of list
     * @return list book
     * @throws Exception
     */
    private ArrayList<BookDTO> loadTopTenBook() throws Exception{
        BookBO bookBo = new BookBO();
        ArrayList<BookDTO> books;
        books = bookBo.getTopTen();
        if(books == null){
            books = new ArrayList<BookDTO>();
        }
        return books;
    }

    private void ReloadBook(HttpServletResponse resp) {
        try {
            BookDTO book = new BookBO().getRandomBook();
            if(book != null){
                PrintWriter out = resp.getWriter();
                out.println("<tr>"
                            + " <td width='84'>"
                                + " <img src=.."+ book.getImgPath() +"width='79' height='83' alt='HinhAnh' class='left' />"
                            + "</td>"
                                + " <td width='58'>"
                                + "<p>" + book.getName() + "</p>"
                                + "<p>" + book.getBookType() + "</p>"
                            + "</td>"
                            + " <td width='51'>"
                                + book.getAuthor()
                            + "</td>"
                            + "<td width='54'>"
                                + book.getPublisher()
                            + "</td>"
                            + "<td width='92'>"
                                + book.getCounter()
                            + "</td>"
                            + "<td "
                                + "style='border: none;'><input type='button' value='>>' onclick='nextRandom()'>"
                            + "</td>"
                        + "</tr>");
            }

//            <tr>
//                         <%
//                         String imgSrc = book.getImgPath();
//                         %>
//                         <td width="84"> <img src=".."<%=imgSrc%> width="79" height="83" alt="HinhAnh" class="left" /></td>
//                         <td width="58"><p><%=book.getName()%></p>
//                             <p><%=book.getBookType()%> </p></td>
//                         <td width="51"><%=book.getAuthor()%></td>
//                         <td width="54"><%=book.getPublisher()%></td>
//                         <td width="92"><%=book.getCounter()%></td>
//                         <td style="border: none;"><input type="button" value=">>" onclick="nextRandom()"></td>
//                     </tr>
        } catch (Exception ex) {
            Logger.getLogger(HomePage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
